package com.ethanzzh.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class StuServlet02 extends HttpServlet {
    

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        sendAddr(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        sendAddr(req, resp);
    }

    public void sendAddr(HttpServletRequest req, HttpServletResponse resp) {
        String path = null;
        String md = req.getParameter("method");
        if (md != null) {
            //查看当前模块中是否有对应的方法，方法的名称和md中的内容一致，方法的参数HttpServletRequest，HttpServletResponse
            //获取到当前模块的字节码
            Class clazz = this.getClass();
            try {
                Method method = clazz.getMethod(md, HttpServletRequest.class, HttpServletResponse.class);
                if (method != null) {
                    //找到了对应的方法，执行当前方法
                    path = (String) method.invoke(this, req, resp);
                }
                if (null != path) {
                    req.getRequestDispatcher(path).forward(req, resp);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String addStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行服务端添加功能");
        //转发到success.jsp
//        req.getRequestDispatcher("/success.jsp").forward(req, resp);
        return "/success.jsp";

    }

    public String delStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行服务端删除功能");
        //转发到success.jsp
//        req.getRequestDispatcher("/success.jsp").forward(req, resp);
        return "/success.jsp";
    }

    public String updateStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行服务端更新功能");
        //由于修改学生这个请求是通过Ajax实现的,是不需要进行转发的，直接响应数据即可
        resp.getWriter().print("updateStuOK");
        return null;
    }

    public String findStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行服务端查找功能");
        //转发到success.jsp
//        req.getRequestDispatcher("/success.jsp").forward(req, resp);
        return "/success.jsp";
    }


}